package com.rd.server.modules.room.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONObject;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.rd.common.exception.BusinessException;
import com.rd.modules.room.model.ao.RoomAO;
import com.rd.modules.room.model.ao.RoomTransferAO;
import com.rd.server.modules.room.mapper.RoomMapper;
import com.rd.server.modules.room.model.RoomPO;
import com.rd.server.modules.room.model.RoomTransferPO;
import com.rd.server.modules.room.model.RoomUsersPO;
import com.rd.server.modules.room.service.RoomService;
import com.rd.server.modules.room.service.RoomTransferService;
import com.rd.server.modules.room.service.RoomUsersService;
import com.rd.server.modules.sse.service.SseService;
import com.rd.server.modules.user.model.po.UserPO;
import com.rd.server.modules.user.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

import static com.rd.server.modules.room.model.table.RoomUsersTableDef.ROOM_USERS;

/**
 * 房间服务实现类
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, RoomPO> implements RoomService {


    @Resource
    private UserService userService;

    @Resource
    private RoomUsersService roomUsersService;

    @Resource
    private RoomTransferService roomTransferService;

    @Resource
    private SseService sseService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transfer(RoomTransferAO transfer) {
        RoomTransferPO roomTransfer = BeanUtil.copyProperties(transfer, RoomTransferPO.class);

        // 付款人
        UserPO payerUser = userService.selectByUserId(StpUtil.getLoginIdAsString());
        roomTransfer.setPayerAvatar(payerUser.getAvatar());
        roomTransfer.setPayerUserId(payerUser.getId());
        roomTransfer.setPayerNickname(payerUser.getNickname());

        // 收款人
        UserPO recipientUser = userService.selectByUserId(transfer.getRecipientUserId());
        roomTransfer.setRecipientNickname(recipientUser.getNickname());

        roomTransferService.save(roomTransfer);

        // 付款人房间账户
        RoomUsersPO roomPayerUser = roomUsersService.selectByUserIdAndRoomId(payerUser.getId(), transfer.getRoomId());
        // 当前的钱 - 输的钱
        roomPayerUser.setCurrentAmount(roomPayerUser.getCurrentAmount().subtract(transfer.getAmount()));

        // 收款人房间账户
        RoomUsersPO roomRecipientUser = roomUsersService.selectByUserIdAndRoomId(recipientUser.getId(), transfer.getRoomId());
        // 当前的钱 + 赢的钱
        roomRecipientUser.setCurrentAmount(roomRecipientUser.getCurrentAmount().add(transfer.getAmount()));

        roomUsersService.updateById(roomPayerUser);
        roomUsersService.updateById(roomRecipientUser);


        // 发送消息
        sseService.sendMessage(JSONObject.toJSONString(roomTransfer));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void closeRoom(RoomAO roomAO) {
        // 1. 查询房间信息
        RoomPO room = this.getById(roomAO.getRoomId());
        if (Objects.isNull(room) || room.getStatus() == 1) {
            // 房间不存在创建房间
            throw new BusinessException("房间不存在或已结算");
        }

        // 2. 查询房间内所有用户
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(ROOM_USERS.ROOM_ID.getName(), roomAO.getRoomId());
        List<RoomUsersPO> roomUsers = roomUsersService.list(queryWrapper);
        if (CollectionUtils.isEmpty(roomUsers)) {
            throw new BusinessException("房间内没有用户");
        }
        // 3. 更新用户对局记录
        for (RoomUsersPO roomUser : roomUsers) {
            UserPO user = userService.selectByUserId(roomUser.getUserId());
            // 更新游戏场次
            user.setGameCount(user.getGameCount() == null ? 1 : user.getGameCount() + 1);
            // 判断胜负（金额增加为胜）
            if (roomUser.getCurrentAmount().compareTo(BigDecimal.ZERO) > 0) {
                user.setWinCount(user.getWinCount() == null ? 1 : user.getWinCount() + 1);
            }
            // 计算胜率
            if (user.getGameCount() > 0) {
                BigDecimal winRate = new BigDecimal(user.getWinCount()).divide(new BigDecimal(user.getGameCount()), 4, BigDecimal.ROUND_HALF_UP)
                        .multiply(new BigDecimal("100"));
                user.setWinRate(winRate);
            }
            userService.updateById(user);
        }
        // 4. 更新房间状态为已结算
        room.setStatus(1);
        this.updateById(room);
    }

    /**
     * 创建房间
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createRoom() {
        String userId = StpUtil.getLoginIdAsString();
        UserPO userPO = userService.selectByUserId(userId);

        // 创建房间
        RoomPO roomPO = new RoomPO();
        roomPO.setCreatedId(userId);
        roomPO.setCreatedBy(userPO.getNickname());
        this.save(roomPO);


        // 发送消息
//        SseMessageVO sseMessageVO = new SseMessageVO();
//        sseMessageVO.setType(MessageType.SYSTEM.getCode());
//        sseMessageVO.setContent("房间已创建");
//        sseService.sendMessage(JSONObject.toJSONString(sseMessageVO));

        // 创建房间 茶水用户自动加入房间
        UserPO TeaWaterUser = userService.selectByUserId("288942432152104960");
        // 加入房间
        roomUsersService.joinRoom(roomPO.getId(), TeaWaterUser);
        return roomPO.getId();
    }

}